<template>
  <ekDialog
    v-model="ekVisiable"
    :title="title"
    @submit="handleSubmit"
    :hideBtn="disabled"
  >
    <div class="ek-form" v-loading="loading">
      <el-form
        :model="form"
        :rules="rules"
        label-width="160px"
        ref="forms"
        :disabled="disabled"
        v-if="!loading"
      >
        <el-form-item prop="user_id" label="用户编号" v-if="loaded">
         
          <ekSelectModel
            v-model="form.user_id"
            :name="detail.user_id_model_text"
            :mapping="{
              label: ['id','user_nick'],
              value: 'id',
            }"
            modelCode="MODEL_USER"
          />
        </el-form-item>
        <el-form-item prop="order_transport_type" label="包裹类型">
          <ekSelectModel
            v-model="form.order_transport_type"
            :name="detail.order_transport_type_model_text"
            :mapping="{
              label: ['transport_type_name'],
              value: 'transport_type_code',
            }"
            modelCode="MODEL_TRANSPORT_TYPE"
          />
        </el-form-item>
         <el-form-item prop="order_shelf_no" label="货架号">
          <ekSelectModel
            v-model="form.order_shelf_no"
            :name="detail.order_shelf_no_model_text"
            :mapping="{
              label: ['shelf_no'],
              value: 'shelf_no',
            }"

            :orders="[{
              field: 'shelf_no',
              sort: 'desc',
            }]"
            modelCode="MODEL_SHELF"
          />
        </el-form-item>

        <el-form-item prop="order_piece" label="包裹件数">
          <ekInput v-model="form.order_piece" />
        </el-form-item>
        <el-form-item prop="order_logistic_no" label="快递单号">
          <ekInput v-model="form.order_logistic_no" :disabled="rowId ? true : false" />
        </el-form-item>
        <el-form-item prop="order_good_length" label="包裹长度（cm）">
          <div class="flex">
            <ekInput v-model="form.order_good_length" class="flex-shrink" />
          </div>
        </el-form-item>
        <el-form-item prop="order_good_width" label="包裹宽度（cm）">
          <div class="flex">
            <ekInput v-model="form.order_good_width" class="flex-shrink" />
          </div>
        </el-form-item>
        <el-form-item prop="order_good_height" label="包裹高度（cm）">
          <div class="flex">
            <ekInput v-model="form.order_good_height" class="flex-shrink" />
          </div>
        </el-form-item>
        <el-form-item prop="order_good_height" label="包裹体积（m³）">
          <div class="flex">
            {{
              (
                (Number(form.order_good_length) *
                  Number(form.order_good_width) *
                  Number(form.order_good_height)) /
                1000000
              ).toFixed(3)
            }}
            m³
          </div>
        </el-form-item>
        <el-form-item prop="order_good_weight" label="包裹重量（kg）">
          <div class="flex">
            <ekInput v-model="form.order_good_weight" class="flex-shrink" />
          </div>
        </el-form-item>

        <el-form-item  label="入库图片">
          <ekUploadImage
            v-model="form.order_inbound_images"
            :action="$uploadUrl"
            :multiple="true"
            accept="image/png,image/jpg,image/jpeg,image/gif,image/bmp"
            :limit="4"
            @on-success="handleSuccess"
          />
        </el-form-item>
        <el-form-item label="附加项" prop="order_items">
          <div class="array-inputs">
       
            <template v-if="form.order_items.length > 0">
              <div
                v-for="(item, index) in form.order_items"
                :key="index"
                class="array-item"
              >
                <ekSelect
                  v-model="item.id"
                  style="width: 25%"
                  placeholder="附加项"
                  :options="itemsOption.map((item) => ({
                    label: item.items_name,
                    value: item.id,
                  }))"
              
                  @change="(event) => handleChange(event, index)"
                />

                <el-input
                  type="number"
                  v-model="item.price"
                  placeholder="附加费用（元）"
                  style="width: 25%"
                />
                <el-select
                  v-model="item.type"
                  placeholder="收费类型"
                  style="width: 25%"
                >
                  <el-option label="可选收费" value="1" />
                  <el-option label="必要收费" value="2" />
                </el-select>
                <el-input
                  v-model="item.desc"
                  placeholder="附加说明"
                  style="width: 25%"
                />
                <el-button type="danger" @click="removeEnvironment(index)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </template>

            <div>
              <el-button type="primary" @click="addEnvironment">新增</el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </ekDialog>
</template>

<script setup>
import {
  watch,
  getCurrentInstance,
  computed,
  reactive,
  ref,
  defineEmits,
} from "vue";
import { Delete } from "@element-plus/icons-vue";
import { apis } from "../data.js";
import ekDialog from "@/components/business/ekDialog/index.vue";
import ekInput from "@/components/form/ekInput/index.vue";
import ekSelect from "@/components/form/ekSelect/index.vue";
import ekTableSelect from "@/components/form/ekTableSelect/index.vue";
import ekSelectModel from "@/components/form/ekSelectModel/index.vue";
import ekUploadImage from "@/components/form/ekUploadImage/index.vue";
import ekTip from "@/components/business/ekTip/index.vue";
import { objectAssignment } from "@/utils/common.js";
const props = defineProps({
  // 显示隐藏
  visiable: {
    type: Boolean,
    default: false,
  },
  rowId: {
    type: [String, Number],
    default: "",
  },
  title: {
    type: String,
    default: "",
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});
const {
  appContext: {
    config: { globalProperties },
  },
} = getCurrentInstance();
const { $storage, $http, $ekLoading, $ekMessage, $imageBaseUrl, $uploadUrl } =
  globalProperties;

const emit = defineEmits(["update:visiable", "submit"]);

// 是否显示
const ekVisiable = computed({
  get() {
    return props.visiable;
  },
  set(value) {
    emit("update:visiable", value);
  },
});

function handleSubmit(done) {
  let url = props.rowId ? apis.edit : apis.add;
  let imgs = [];
  console.log(
    form.value.order_inbound_images,
    "form.value.order_inbound_images"
  );
  if (form.value.order_inbound_images) {
    imgs = JSON.parse(form.value.order_inbound_images).map((item) => item.path);
  }

  forms.value.validate((valid) => {
    if (valid) {
      $http
        .request({
          url: url,
          method: props.rowId ? "PUT" : "POST",
          data: {
            ...form.value,
            order_inbound_images: imgs,
          },
        })
        .then((res) => {
          $ekMessage.success(res.message);
          emit("submit", done);
        })
        .catch((err) => {});
    }
  });
}
const loading = ref(false);
let forms = ref(null);
let form = ref({});
const detail = ref({});
const initData = () => {
  loaded.value = false;
  form.value = {
    order_transport_type: "",
    order_piece: 1,
    order_logistic_no: "",
    order_good_length: "",
    order_good_width: "",
    order_good_height: "",
    order_good_weight: "",
    order_shelf_no: "",
    order_inbound_images: "",
    order_items: [],
    user_id: "",
    id: props.rowId,
  };
  detail.value = {
    user_id_model_text: "",
    order_shelf_no_model_text: "",
  };
};

let rules = reactive({
  user_id: [{ required: true, message: "请选择用户", trigger: "blur" }],
  order_transport_type: [
    { required: true, message: "请选择包裹类型", trigger: "blur" },
  ],
  order_piece: [{ required: true, message: "请输入包裹件数", trigger: "blur" }],
  order_logistic_no: [
    { required: true, message: "请输入快递编号", trigger: "blur" },
  ],
  order_shelf_no: [{ required: true, message: "请选择货架号", trigger: "blur" }],
  order_items: [
    {  message: "请选择附加项", trigger: "blur",validator: (rule, value, callback) => {
      if (value.length > 0) {
        for(let i in value){
          if(!value[i].id){
            callback(new Error("请选择附加项"));
          }
           if(!value[i].price > 0){
            callback(new Error("附加项费用必须大于0"));
          }
        }
        callback();
      } else {
        callback();
      }
    } },
  ],
});
// 环境变量
const addEnvironment = () => {
  // id 附加项原始id，附加项名称，附加项描述，附加项费用，收费类型
  form.value.order_items.push({ id: null, name: "", desc: "", price: 0, type: "1" });
};
const removeEnvironment = (index) => {
  form.value.order_items.splice(index, 1);
};
const handleChange = (event,index) => {
  let data = itemsOption.value.find((item) => item.id == event);
  if(data){
    form.value.order_items[index].name = data.items_name;
    form.value.order_items[index].type = data.items_type;
    form.value.order_items[index].desc = data.items_remark;
  }
};
const handleSuccess = (response, file, fileList) => {
  console.log(response, file, fileList);
};
// 初始化表单
const loaded = ref(false);
async function init() {
  loading.value = true;
  // 详情或者编辑
  if (props.rowId) {
    $http
      .get(apis.getOrderDetail, {
        params: {
          id: props.rowId,
        },
      })
      .then((res) => {
        if (Object.keys(res.data).length) {
          detail.value = {
            ...detail.value,
            ...res.data,
          };

          objectAssignment(form.value, res.data);
          if (form.value.order_inbound_images) {
            let images = JSON.parse(form.value.order_inbound_images);
            let newImages = [];
            for (let i in images) {
              newImages.push({ url: $imageBaseUrl + images[i] });
            }
            form.value.order_inbound_images = JSON.stringify(newImages);
          }
          console.log(form.value, "form.valueform.value");
        }
        loaded.value = true;
        loading.value = false;
      });
  } else {
    loaded.value = true;
    loading.value = false;
  }
}
const itemsOption = ref([]);
async function initItems() {
  // 初始化附加项
  $http
    .get(apis.getItems)
    .then((res) => {
      if(res.status == 'success'){
        itemsOption.value = res.data || [];
      }
    });
}
watch(
  () => props.visiable,
  (val) => {
    if (val) {
      initData();
      init();
      // 初始化附加项
      initItems()
    }
  }
);

</script>

<style scoped lang="scss">
.array-inputs {
  text-align: left;
  .array-item {
    display: flex;
    gap: 8px;
    margin-bottom: 8px;
    align-items: flex-start;

    .el-input,
    .el-input-number {
      flex: 1;
    }
  }
}
</style>
